<template>
<div class="detail-container">
  <div class="index-container">
    <div class="naviga">产品能力分析&nbsp;>  <span class="navigaActive">产品分析详情</span></div>
    <div class="mainPage" style="background: #E8EEF4">
      <div class="summaryHeader">
      <span class="lightYellow">{{catagrayCount}}</span>个品类，<span class="lightYellow">{{productCount}}</span>个产品型号，其中<span class="lightYellow">{{onLine}}</span>个型号在售，<span class="lightYellow">{{offLine}}</span>个型号下市
      </div>
      <div class="whitePage">
        <circle-compent :detailCatagrayCount="catagrayCount" :detailProductCount="productCount"
          :detailOnLine="detailOnLine" :detailOffLine="detailOffLine" :titleName="titleName"></circle-compent>
        <div class="sourceContainer" style="margin: 0px 12px;border: 1px solid #e3e2e2">
          <div class="sourceHeader">
            <div class="conditionContainer flex-container space-between" style="height: 40px;align-items: center;">
              <div class="flex-item"  v-if="toggleSwitch">
                <el-form :inline="true" class="demo-form-inline single-form-inline" size="small">
                  <el-radio-group  size="small" v-model="selectMonth" @change="timeSelect">
                    <el-radio-button label="monthly">最近1个月</el-radio-button>
                    <el-radio-button label="last_quarter">最近3个月</el-radio-button>
                  </el-radio-group>
                  <el-form-item>
                    <el-date-picker @change="daterange" v-model="productType" type="daterange" size="small" align="center"
                                    value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="secondary" @click="multiSearch()">组合查询</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div class="flex-item" v-else>
                <el-form :inline="true"  class="demo-form-inline single-form-inline" size="small">
                  <el-form-item label="查询类型">
                    <el-select v-model="selectType" placeholder="" style="width: 150px;">
                      <el-option label="产品型号" value="code"></el-option>
                      <el-option label="产品名称" value="name"></el-option>
                    </el-select>
                    <el-input style="width: 200px" v-if="selectType == 'code'" v-model="inputCode" placeholder="请输入产品型号" size="small"></el-input>
                    <el-input style="width: 200px" v-else v-model="inputName" placeholder="请输入产品名称" size="small"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-date-picker v-model="searchSetData" type="daterange" size="small" align="center" :clearable="false"
                                    value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item>
                    <el-button size="small" type="primary" @click="searchCodeName">查询</el-button>
                  </el-form-item>
                </el-form>
              </div>
              <div class="flex-item">
                <el-button type="text" v-if="toggleSwitch" @click="toggleSwitch = false">查询产品型号/名称</el-button>
                <el-button type="text" v-else @click="toggleSwitch = true;">组合查找</el-button>
              </div>
            </div>
          </div>
          <div class="tableContainer">
            <el-table :data="results" style="min-width: 100%" size="mini">
              <el-table-column
                type="index"
                width="80px"
                label="序号">
              </el-table-column>
              <el-table-column
                width="125px"
                prop="productCode"
                label="产品型号">
              </el-table-column>
              <el-table-column
                width="215px"
                prop="productName"
                label="产品名称">
              </el-table-column>
              <el-table-column
                prop="category"
                width="120px"
                label="所属品类">
              </el-table-column>
              <el-table-column
                sortable
                prop="saleAmount"
                :formatter="formatterPrice"
                label="销售额(万元)">
              </el-table-column>
              <el-table-column
                sortable
                prop="saleCount"
                label="销售量(件)">
              </el-table-column>
              <el-table-column
                prop="isSale"
                label="状态">
              </el-table-column>
              <el-table-column
                sortable
                prop="averagePrice"
                label="平均售价(元)">
              </el-table-column>
              <!--<el-table-column-->
                <!--sortable-->
                <!--prop="percentage"-->
                <!--label="市场占有率">-->
              <!--</el-table-column>-->
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <div class="opreator" @click="detailRowSet(scope.row)">详情</div>/
                  <div class="opreator" @click="contrastRowProd(scope.row)">产品对比</div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="paginationSet">
          <div class="pagination-container">
            <div class="toStart" @click="setCurrentPage">首页</div>
            <el-pagination background layout="prev, pager, next" @current-change="pageChangeSet"
                           :current-page.sync="currentPage" :total="page">
            </el-pagination>
          </div>
        </div>
        <div>
          </div>
      </div>
    </div>
  </div>
  <!--  dialog-container -->
  <div class="dialog-container">
    <!--  Search-Dialog -->
    <div class="search-dialog">
      <el-dialog title="组合查询" :visible.sync="multiSelect" top="8vh" :show-close="false" width="80%" center :before-close="handleClose">
        <div>
          <div class="box-colum">
            <el-form>
              <el-form-item label="品类：">
                <el-radio-group v-model="categorySet" @change="oneCategoryChange">
                  <el-radio v-for="(item,index) in allCateSet" :key="index" :label="item.categoryName" :value="item.categoryName"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="状态：">
                <el-select v-model="saleMarket" placeholder="" style="width: 150px" size="small">
                  <el-option label="全部" value="2"></el-option>
                  <el-option label="在售" value="1"></el-option>
                  <el-option label="下市" value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="销售均价：">
                <el-input type="number" :min="0" size="small" v-model="firstAveragePrice" placeholder="请输入均价"></el-input>
                ----
                <el-input type="number" :min="0" size="small" v-model="lastAveragePrice" placeholder="请输入均价"></el-input>
              </el-form-item>

              <el-form-item :label="item.specificationName" v-for="(item,index) in singleCate" :key="index">
                <el-checkbox :indeterminate="item.indeterminate" :data-indx="index" v-model="item.checkAll" @change="checked => handleCheckAllChange(checked,item)">全选</el-checkbox>
                <el-checkbox-group v-model="item.checkedCities" @change="checked => handleCheckedCitiesChange(checked,item)">
                  <el-checkbox v-for="it in item.specificationValue" :label="it" :key="it">{{it}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" type="primary" @click="allSelSearch">查 询</el-button>
          <el-button size="small" @click="multiSelect = false">取 消</el-button>
          <el-button size="small" @click="reSetData(categorySet)">重 置</el-button>
        </span>
      </el-dialog>
    </div>
    <!--  详情Dialog  -->
    <detail-dialog :showdialog.sync="detailDialogTableVisible" :productCode="pid" :searchDate="searchDateSet"></detail-dialog>
    <!--  异常分析Dialog  -->
    <outlier-analysis v-if="compareItemsProd.length > 0" :category-id="cateSetActive.categoryId"
                      :showdialog.sync="analysisDialogTableVisible" :product-code="cateSetActive.productCode" ></outlier-analysis>
  </div>
</div>
</template>
<script>
  import DetailDialog from './detailDialog'
  import CircleCompent from 'router/marketSale/compentSet/circleCompent'
  import { mapGetters, mapMutations, mapActions } from 'vuex'
  import OutlierAnalysis from '../singleProduct/outlierAnalysis'
  import * as opreate from 'api/getData'
  const dateMap = new Map([
    ['monthly',{ num: 1 }],
    ['last_quarter',{ num: 3 }]
  ])
  const nowSetDate = new Date()

  export default {
    data() {
      return ({
        cateSetActive:{},
        firstAveragePrice:'',
        lastAveragePrice:'',
        selectMonth:'last_quarter',
        saleMarket:'2',
        categorySet:'',
        multiSelect:false,
        selectType:'code',
        currentPage:1,
        productType:[],
        catagrayCount: '',
        productCount: '',
        onLine: '',
        offLine: '',
        detailCatagrayCount: '',
        detailProductCount: '',
        detailOnLine: '',
        detailOffLine: '',
        results: [],
        dateValue: {},
        toggleSwitch:true,
        detailDialogTableVisible: false,
        checkAll: false,
        checkedCities: [],
        isIndeterminate: true,
        pid:'',
        inputCode: '',
        inputName:'',
        compareItems: [],
        analysisDialogTableVisible: false,
        titleName:[
          '品类数（个）',
          '型号数（个）',
          '销售量（万件）',
          '销售额（万元）'
        ],
        allCateSet: [],
        singleCate: '',
        listParam: [],
        page:1,
        selectFlag: '1',
        searchSetData: [
          new Date(nowSetDate.getFullYear(),(nowSetDate.getMonth() - 12),nowSetDate.getDate()).format('yyyy-MM-dd'),
          nowSetDate.format('yyyy-MM-dd')
        ],
        searchDateSet: {}
      })
    },
    computed:{
      ...mapGetters(["compareItemsProd"]),
      searchDate:{
        set:function () {},
        get:function () {
          let [ firstTime, lastTime ] = this.productType
          let tempSet = this.toggleSwitch ? (this.productType.length > 0 ? { firstTime, lastTime } : (dateMap.get(this.selectMonth) || { num: 12 })) : { num: 12 }
          return tempSet
        }
      }
    },
    components:{
      DetailDialog,
      CircleCompent,
      OutlierAnalysis
    },
    mounted() {
      this.getDataSetInit()
      this.getListInfo(1,'last_quarter')
    },
    methods: {
      ...mapMutations(["updateProdCtrolStateInfo","updateCompareItemsProd"]),
      ...mapActions(["obtainRenderOrganization","obtainCompCodeAndBrandByCate"]),
      formatterPrice(row, column){
        return parseFloat((row.saleAmount || 0)/10000).toFixed(2)
      },
      searchSetDataChange(searchSetData){
        let { dateStart, dateEnd } = searchSetData
        this.searchSetData = Object.assign(this.searchSetData, searchSetData)
      },
      pageChangeSet(){
        '1' == this.selectFlag
          ?  this.getListInfo(this.currentPage,this.selectMonth,this.inputName,this.inputCode)
          : this.allSelNext()
      },
      oneCategoryChange(newVal){
        let indexSet = this.allCateSet.findIndex(v => v.categoryName == newVal)
        this.singleCate = indexSet > -1 ? JSON.parse(JSON.stringify(this.allCateSet[indexSet].list)) : []
      },
      reSetData(categorySet){
        let indexSet = this.allCateSet.findIndex(v => v.categoryName == categorySet)
        this.saleMarket = '2'
        this.firstAveragePrice = ''
        this.lastAveragePrice = ''
        if(indexSet > -1){
          let tempSet = JSON.parse(JSON.stringify(this.allCateSet))
          tempSet = tempSet[indexSet] ?  tempSet[indexSet] : {}
          this.categorySet = tempSet.categoryName || ''
          this.singleCate = tempSet.list || []
        }else {
          this.$message.error('系统错误，请稍后再试')
        }
      },
      searchCodeName(){
        this.selectFlag = '1'
        this.currentPage = 1
        this.selectType == 'code' ? this.inputName = '' : this.inputCode = ''
        this.getListInfo(this.currentPage,'',this.inputName,this.inputCode)
      },
      allSelSearch(){
        this.multiSelect = false
        this.currentPage = 1
        this.selectFlag = '2'
        this.listParam = [].concat(...this.singleCate.map(v => v.checkedCities))
        this.allSelNext()
      },
      allSelNext(){
        this.searchDateSet = this.toggleSwitch ? this.searchDate : { firstTime, lastTime }
        opreate.multiSelects({
          ...this.searchDateSet,
          pageNum:this.currentPage,
          category:this.categorySet,
          isSale:this.saleMarket,
          firstAveragePrice:this.firstAveragePrice,
          lastAveragePrice:this.lastAveragePrice,
          listParam:this.listParam
        }).then(res => {
          let listSet = res.data.list || []
          this.results = listSet.map(item => {
            item.isSale = item.isSale == '0' ? '下市' : '在售'
            return item
          })
          this.page = res.data.totalRecord
        })
      },
      multiSearch(index = 0){
        opreate.productMessage().then(res => {
          if('200' == res.code){
            let tempSet = res.data || []
            this.multiSelect = true
            let tempSetIndex = tempSet[index] ?  tempSet[index] : {}
            this.categorySet = tempSetIndex.categoryName || ''
            this.singleCate = tempSetIndex.list || []
            this.allCateSet = JSON.parse(JSON.stringify(tempSet))
          }else {
            this.$message.error('系统错误，请稍后再试')
          }
        })
      },
      daterange(newVal){
        this.getListInfo(this.currentPage,'','','')
        this.selectMonth = ''
        this.inputCode = ''
        this.inputName = ''
        this.selectFlag = '1'
      },
      timeSelect(dateTime){
        this.currentPage = 1
        this.inputCode = ''
        this.inputName = ''
        this.productType = []
        this.getListInfo(this.currentPage,dateTime)
        this.selectFlag = '1'
      },
      handleCheckAllChange(val,item) {
        item.checkedCities = val ? item.specificationValue : [];
        item.indeterminate = false;
      },
      handleCheckedCitiesChange(value,item) {
        let checkedCount = value.length;
        item.checkAll = checkedCount == item.specificationValue.length;
        item.indeterminate = checkedCount > 0 && checkedCount < item.specificationValue.length;
      },
      handleClose(done) {

      },
      getDataSetInit() {
        opreate.productNumber().then(res => {
          this.catagrayCount = res.data.totalCategory
          this.productCount = res.data.totalProductCode
          this.onLine = res.data.onlineSaleCount
          this.offLine = res.data.offlineSaleCount
          this.detailOnLine =( res.data.totalSaleCount/10000).toFixed(0)
          this.detailOffLine = (res.data.totalSaleAmount/10000).toFixed(0)
        })
      },
      getListInfo(pageNumber,dateTime,productName,productCode){
        let [ firstTime, lastTime ] = this.toggleSwitch ? this.productType : this.searchSetData
        opreate.productAnalysis({ pageNumber,dateTime,productName,productCode,firstTime,lastTime }).then(res => {
          let { list = [],  totalRecord = 0 } = res.data || {}
          this.results = list.map(v => {
            return { ...v, isSale: v.isSale == '0' ? '下市' : '在售' }
          })
          this.page = totalRecord
        })
      },
      setCurrentPage(){
        this.currentPage = 1
        this.pageChangeSet()
      },
      detailRowSet(rowSet){
        let [ firstTime, lastTime ] = this.searchSetData
        this.searchDateSet = this.toggleSwitch ? this.searchDate : { firstTime, lastTime }
        this.detailDialogTableVisible = true
        this.pid = rowSet.productCode
      },
      async contrastRowProd(rowSet){
        const { productCode, categoryId } = rowSet
        this.cateSetActive = { productCode, categoryId }
        opreate.getStartAnalysis({
          timeNumber: "6",
          productCodeList:[ productCode ]
        }).then(res => {
          if(200 == res.code && res.data){
            this.cateActive = categoryId
            this.updateCompareItemsProd({ payload: res.data, flag: true })
            this.analysisDialogTableVisible = true
          }else {
            this.$message.error('错了哦，请稍后再试')
          }
        })
      },
    }
  }
</script>

<style lang="less" scoped>
  .box-colum .el-input--small{
    width: 200px;
  }
  .whitePage{
    background-color: #ffffff;
    margin: 0 10px;
  }
  .el-checkbox{
    margin-right: 20px!important;
  }
  .el-checkbox-group{
    display: inline-block;
    margin-left: 30px;
  }
  .tableContainer{
    margin: 0 10px;
    border: 1px solid #e3e2e2;
  }
  .el-radio-group  > .el-radio{
    margin-right: 15px!important;
  }
  .single-form-inline .el-form-item{
    margin: 0!important;
  }
  .pickerOption{
    display: inline-block;
  }
  .single-form-inline .el-form-item{
    margin: 2px 0 0 0;
  }
</style>
